package 宝贝复制;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by User on 2017/9/27.
 */
public class FileUtil {

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static void print(String fileName, String content) {
        String format = simpleDateFormat.format(new Date());
        File file;
        if (fileName.endsWith(".xml")) {
            file = new File("C:\\Users\\User\\IdeaProjects\\zql\\src\\main\\resources\\tm宝贝复制\\" + format + "\\" + fileName);
        } else {
            file = new File("C:\\Users\\User\\IdeaProjects\\zql\\src\\main\\resources\\tm宝贝复制\\" + format + "\\" + fileName + ".json");
        }
        int i = 1;
        while (file.exists()) {
            if (fileName.endsWith(".xml")) {
                file = new File("C:\\Users\\User\\IdeaProjects\\zql\\src\\main\\resources\\tm宝贝复制\\" + format + "\\" + fileName + i);
            } else {
                file = new File("C:\\Users\\User\\IdeaProjects\\zql\\src\\main\\resources\\tm宝贝复制\\" + format + "\\" + fileName + i + ".json");
            }
            i++;
        }

        if(!file.getParentFile().exists()) {
            //如果目标文件所在的目录不存在，则创建父目录
            System.out.println("目标文件所在目录不存在，准备创建它！");
            if(!file.getParentFile().mkdirs()) {
                System.out.println("创建目标文件所在目录失败！");
                return;
            }
        }

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(content.getBytes());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println(file.getName() + " write success !!!");
    }

}
